#!/usr/bin/env python

import os.path
import sys

from sparrow.compiler import analyzer
import sparrow.compiler.util

def process_file(filename, options):
  def print_output(*args):
    if options.verbose:
      print >> sys.stderr, ' '.join(args)

  try:
    opt = analyzer.optimizer_map[options.optimizer_level]
    opt.collapse_optional_whitespace = options.ignore_optional_whitespace
    src_code = sparrow.compiler.util.compile_file(
      filename, write_file=True, options=opt)
  except Exception, e:
    print >> sys.stderr, "FAILED:", filename, e
    raise


if __name__ == '__main__':
  from optparse import OptionParser
  op = OptionParser()
  op.add_option('--preserve-optional-whitespace', action='store_false',
                default=True, dest='ignore_optional_whitespace',
                help='preserve leading whitespace before a directive')
  op.add_option('-v', '--verbose', action='store_true', default=False)
  op.add_option('-O', dest='optimizer_level', type='int', default=0)
  (options, args) = op.parse_args()

  for filename in args:
    process_file(filename, options)
